import * as step from '@flow-step/step-toolkit'
import {SaeInterface} from './sae'
import {AbortAndRollbackChangeOrderRequest, AbortAndRollbackChangeOrderResponse} from '@alicloud/sae20190506'
import {IParams} from './params'
export async function terminate(params:IParams, sae: SaeInterface) {
    if (!params.CHANGE_ORDER_ID) {
        throw new Error('CHANGE_ORDER_ID is not set in environment variables');
    }

    step.info(`TERMINATING DEPLOYMENT, changeOrderId: ${params.CHANGE_ORDER_ID} `)

    const request = new AbortAndRollbackChangeOrderRequest({
        changeOrderId: params.CHANGE_ORDER_ID,
    })
    let response: AbortAndRollbackChangeOrderResponse
    try {
        response = await sae.abortAndRollbackChangeOrder(request)
    }catch (error){
        throw new Error(`failed to abortAndRollbackChangeOrder: ${error}`)
    }

    if (response.body?.code != '200') {
        throw new Error(`failed to terminate the task, code: ${response.body?.code}, message: ${response.body?.message}`)
    }

    step.info(`CURRENT DEPLOYMENT IS TERMINATED `)

}